<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require_once 'sitecontroller.php';

class Login extends SiteController {
    
    public function index() {
        
        $user = null;
        
        if ($this->session->userdata('userId') == FALSE) {
            $this->load->library('form_validation');

            $this->form_validation->set_rules('email', 'Email', 'required|valid_email|callback_email_check' );
            $this->form_validation->set_rules('senha', 'Senha', 'required|callback_password_check' );
            
            if ($this->form_validation->run ()) {
                $user = $this->doctrine->em->getRepository ( 'Entities\Usuario' )->findOneBy ( array (
                                'email' => $this->input->post ( 'email' ) 
                ) );
            }
        } else if ($this->session->userdata ( 'userId' ) != FALSE) {
            $user = $this->doctrine->em->find ( 'Entities\Usuario', $this->session->userdata ( 'userId' ) );
        }

        if ($user instanceof Entities\Usuario) {
            $this->session->set_userdata ( array (
                'userId' => $user->getId () 
            ) );
            if ($user->getNivel() > 0){
                redirect ( '/chamado/lista/pendentes' );
            } else {
                redirect ( '/chamado/lista' );
            }
        } else {
            $this->loadView ();
        }
        
    }
    
    public function email_check() {
        $user = $this->doctrine->em->getRepository ( 'Entities\Usuario' )->findOneBy ( array (
            'email' => $this->input->post ( 'email' ) 
        ) );
        if (is_null ( $user )) {
            return FALSE;
        } else {
            return TRUE;
        }
    }
    
    public function password_check() {
        $user = $this->doctrine->em->getRepository ( 'Entities\Usuario' )->findOneBy ( array (
            'email' => $this->input->post ( 'email' ) 
        ) );
        if (is_null ( $user )) {
            return FALSE;
        } else if (md5 ( $this->input->post ( 'senha' ) ) == $user->getSenha()) {
            return TRUE;
        } else {
            return FALSE;
        }
    }
    
}

